package com.bantang.service.impl;

import com.bantang.common.ErrorCode;
import com.bantang.exception.ThrowUtils;
import com.bantang.mapper.ChartMapper;
import com.bantang.model.entity.Chart;
import com.bantang.service.ChartService;
import com.bantang.utils.SqlUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 *
 */
@Service
public class ChartServiceImpl extends ServiceImpl<ChartMapper, Chart>
    implements ChartService {

    @Resource
    ChartMapper chartMapper;


    final static String PREFIX = "chart";
    @Override
    public boolean saveData(String charData,Long id,Long chartId) {

        //TODO 1.先创建一张表
        // 1.1 根据charData 生成一条sql语句
        String createSql = genCreateSqlByCharData(charData,id,chartId);
        // 1.2 通过sql语句进行创建表
        int createResult = chartMapper.createCharDataTable(createSql);

        //TODO 2.再将数据存入表中
        // 2.1 生成新增语句
        String insertSql = genInsertSqlByCharData(charData,id,chartId);

        // 2.1 执行sql语句
        int insertResult = chartMapper.insertCharData(insertSql);


        return true;
    }

    private String genCreateSqlByCharData(String charData,Long id,Long chartId){

        ThrowUtils.throwIf(!SqlUtils.validSqlField(charData), ErrorCode.PARAMS_ERROR,"同行别干坏事哦");


        String cols[]  = charData.split("\n")[0].split(",");

        StringBuffer contains = new StringBuffer();
        for (String col : cols) {
            contains.append(col).append(" varchar(100) null ,");
        }

        contains.deleteCharAt(contains.length()-1);

        String sql = "create table "+PREFIX+"_"+id+"_"+chartId+"("+contains+");";


        return sql;
    }
    private String genInsertSqlByCharData(String charData,Long id,Long chartId){
        ThrowUtils.throwIf(!SqlUtils.validSqlField(charData), ErrorCode.PARAMS_ERROR,"同行别干坏事哦");
        String cols[]  = charData.split("\n");

        StringBuffer contains = new StringBuffer("insert into ");
        contains.append(PREFIX).append("_").append(id).append("_").append(chartId).append(" values");


        for (int i = 1; i < cols.length; i++) {
            String col = cols[i];
            contains.append("(");

            String values [] = col.split(",");
            for (String value : values) {
                contains.append("'").append(value).append("',");
            }
            if (values.length > 0){
                contains.deleteCharAt(contains.length()-1);
            }
            contains.append("),");
        }
        contains.deleteCharAt(contains.length()-1);

        contains.append(";");
        return contains.toString();
    }

}




